package cn.edu.zjicm.wordsnet_d.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.data.StaticData;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class ShareUtil {
	private Context context;
	private Oauth2AccessToken mAccessToken;
	private IWeiboShareAPI mWeiboShareAPI;

	public ShareUtil(Context context, Utils.shareWay shareWay, Bitmap mBitmap, String imageURL, String title, String content, String Url) {
		this.context = context;
		switch (shareWay) {
		case wechat:
			initWechat(mBitmap, title, content, Url);
			break;
		case wechatTimeline:
			initWechatTimeline(mBitmap, title, content, Url);
			break;
		case QQ:
			initQQ(imageURL, title, content, Url);
			break;
		case QZone:
			initQZone(imageURL, title, content, Url);
			break;
		case weibo:
			initWeiBo(mBitmap, title, content, Url);
			break;
		}
	}

	private void initWechat(Bitmap mBitmap, String title, String content, String Url) {
		final String APP_ID_WECHAT = StaticData.APP_ID_WECHAT;
		IWXAPI apiWechat;
		apiWechat = WXAPIFactory.createWXAPI(context, APP_ID_WECHAT);
		apiWechat.registerApp(APP_ID_WECHAT);

		if (apiWechat.isWXAppInstalled()) {
			WXWebpageObject localWXWebpageObject = new WXWebpageObject();
			localWXWebpageObject.webpageUrl = Url;
			WXMediaMessage localWXMediaMessage = new WXMediaMessage(localWXWebpageObject);
			localWXMediaMessage.title = title;
			localWXMediaMessage.description = content;
			localWXMediaMessage.thumbData = bmpToByteArray(imageZoom(mBitmap, 30.00), true);
			SendMessageToWX.Req localReq = new SendMessageToWX.Req();
			localReq.transaction = System.currentTimeMillis() + "";
			localReq.message = localWXMediaMessage;
			apiWechat.sendReq(localReq);
		} else {
			Toast.makeText(context, "安装微信客户端后才能分享哦", Toast.LENGTH_SHORT).show();
		}
	}

	private void initWechatTimeline(Bitmap mBitmap, String title, String content, String Url) {
		final String APP_ID_WECHAT = StaticData.APP_ID_WECHAT;
		IWXAPI apiWechat;
		apiWechat = WXAPIFactory.createWXAPI(context, APP_ID_WECHAT);
		if (apiWechat.isWXAppInstalled()) {
			apiWechat.registerApp(APP_ID_WECHAT);
			WXWebpageObject localWXWebpageObject = new WXWebpageObject();
			localWXWebpageObject.webpageUrl = Url;
			WXMediaMessage localWXMediaMessage = new WXMediaMessage(localWXWebpageObject);
			localWXMediaMessage.title = content;
			localWXMediaMessage.thumbData = bmpToByteArray(imageZoom(mBitmap, 30.00), true);
			SendMessageToWX.Req localReq = new SendMessageToWX.Req();
			localReq.transaction = System.currentTimeMillis() + "";
			localReq.message = localWXMediaMessage;
			localReq.scene = localReq.WXSceneTimeline;// 微信朋友圈
			apiWechat.sendReq(localReq);
		} else {
			Toast.makeText(context, "安装微信客户端后才能分享哦", Toast.LENGTH_SHORT).show();
		}
	}

	private void initQQ(String imageURL, String title, String content, String Url) {
		final String APP_ID_QQ = StaticData.APP_ID_QQ;
		final Tencent mTencent = Tencent.createInstance(APP_ID_QQ, context.getApplicationContext());

		final Bundle params = new Bundle();
		params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, Url);
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageURL);
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "知米背单词");
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		// params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 0x00);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTencent.shareToQQ((Activity) context, params, new IUiListener() {
					@Override
					public void onCancel() {
					}

					@Override
					public void onComplete(Object response) {
					}

					@Override
					public void onError(UiError e) {
					}
				});
			}
		}).start();
	}

	private void initQZone(String imageURL, String title, String content, String Url) {
		final Tencent mTencent = Tencent.createInstance(StaticData.APP_ID_QQ, context.getApplicationContext());
		final Bundle params = new Bundle();
		params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, Url);
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageURL);
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "知米背单词");

		params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);// QQ空间
		mTencent.shareToQQ((Activity) context, params, new IUiListener() {
			@Override
			public void onCancel() {
			}

			@Override
			public void onComplete(Object response) {
			}

			@Override
			public void onError(UiError e) {
			}
		});
	}

	String weiboTitle, weiboContent, weiboUrl;

	private void initWeiBo(Bitmap mBitmap, String title, String content, String Url) {
		this.weiboTitle = title;
		this.weiboContent = content;
		this.weiboUrl = Url;
		final String APP_KEY_SINA_WEIBO = StaticData.APP_KEY_SINA_WEIBO;
		mWeiboShareAPI = null;
		final WeiboAuth mWeiboAuth;
		/** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
		SsoHandler mSsoHandler;

		String token = AppPreference.getAccessTokenWeibo(context);
		if (token != null)
			mAccessToken = Oauth2AccessToken.parseAccessToken(token);
		if (mAccessToken != null && mAccessToken.isSessionValid()) {
			if (!mWeiboShareAPI.isWeiboAppInstalled()) {
				sendWeibo(content + "   " + Url);
			} else {
				ImageObject imageObject = new ImageObject();
				// 创建文本消息对象。
				TextObject textObject = new TextObject();

				imageObject.setImageObject(mBitmap);
				textObject.text = content + "   " + Url;
				// 1. 初始化微博的分享消息
				WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
				weiboMessage.textObject = textObject;
				weiboMessage.imageObject = imageObject;
				// 2. 初始化从第三方到微博的消息请求
				final SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest(); // 用transaction唯一标识一个请求
				request.transaction = String.valueOf(System.currentTimeMillis());
				request.multiMessage = weiboMessage;
				// 3. 发送请求消息到微博,唤起微博分享界面
				mWeiboShareAPI.sendRequest(request);
			}
		} else {

			// 创建微博实例
			mWeiboAuth = new WeiboAuth(context, APP_KEY_SINA_WEIBO, StaticData.REDIRECT_URL, StaticData.SCOPE);
			mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(context, APP_KEY_SINA_WEIBO);

			// 判断用户手机是否安装微博客户端
			if (mWeiboShareAPI.isWeiboAppInstalled()) {
				// 用户手机安装了微博客户端，通过单点登录 (SSO) 获取 Token
				mSsoHandler = new SsoHandler((Activity) context, mWeiboAuth);
				mSsoHandler.authorize(new AuthListener());
				// 注册第三方应用 到微博客户端中,注册成功后该应用将显示在微博的应用列表中。
				mWeiboShareAPI.registerApp();

				ImageObject imageObject = new ImageObject();
				// 创建文本消息对象。
				TextObject textObject = new TextObject();

				imageObject.setImageObject(mBitmap);
				textObject.text = content + "   " + Url;
				// 1. 初始化微博的分享消息
				WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
				weiboMessage.textObject = textObject;
				weiboMessage.imageObject = imageObject;
				// 2. 初始化从第三方到微博的消息请求
				final SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest(); // 用transaction唯一标识一个请求
				request.transaction = String.valueOf(System.currentTimeMillis());
				request.multiMessage = weiboMessage;
				// 3. 发送请求消息到微博,唤起微博分享界面
				mWeiboShareAPI.sendRequest(request);

			} else if (!mWeiboShareAPI.isWeiboAppInstalled()) {
				// 用户手机没有安装了微博客户端，通过应用签名信息获取 Token
				((Activity) context).runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						mWeiboAuth.anthorize(new AuthListener());
					}
				});
			}
		}

	}

	class AuthListener implements WeiboAuthListener {

		// 登录成功
		@Override
		public void onComplete(final Bundle values) {
			// 从 Bundle 中解析 Token
			new Thread(new Runnable() {
				@Override
				public void run() {
					Looper.prepare();
					mAccessToken = Oauth2AccessToken.parseAccessToken(values);
					AppPreference.setAccessTokenWeibo(context, mAccessToken.toString());
					if (mAccessToken.isSessionValid()) {
						Toast.makeText(context, "授权成功", Toast.LENGTH_SHORT).show();
						if (!mWeiboShareAPI.isWeiboAppInstalled()) {
							sendWeibo(weiboContent + "    " + weiboUrl);
						}
					} else {
						// 当您注册的应用程序签名不正确时，就会收到 Code，请确保签名正确
						String code = values.getString("code");
						String message = "授权失败";
						if (!TextUtils.isEmpty(code)) {
							message = message + "\nObtained the code: " + code;
						}
						Toast.makeText(context, message, Toast.LENGTH_LONG).show();
						Looper.loop();
					}
				}
			}).start();
		}

		@Override
		public void onCancel() {
			Toast.makeText(context, "取消授权", Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(context, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	private String TAG = "发送微博";

	// 发送微博
	protected void sendWeibo(String string) {
		/*
		 * 无客户端发送图文：http://blog.csdn.net/hellohaifei/article/details/9707089
		 * http://blog.csdn.net/mrlixirong/article/details/8246227
		 */
		// 组织post参数
		List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("status", string));
		params.add(new BasicNameValuePair("access_token", mAccessToken.getToken()));
		HttpClient httpClient = new DefaultHttpClient();
		// 传入post方法的请求地址，即发送微博的api接口
		HttpPost postMethod = new HttpPost("https://api.weibo.com/2/statuses/update.json");
		try {

			postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
			HttpResponse httpResponse = httpClient.execute(postMethod);
			// 将返回结果转为字符串，通过文档可知返回结果为json字符串，结构请参考文档
			String resultStr = EntityUtils.toString(httpResponse.getEntity());
			Log.e(TAG, resultStr);
			// 从json字符串中建立JSONObject
			JSONObject resultJson = new JSONObject(resultStr);
			// 如果发送微博失败的话，返回字段中有"error"字段，通过判断是否存在该字段即可知道是否发送成功
			if (resultJson.has("error")) {
				Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(context, "发送成功", Toast.LENGTH_SHORT).show();
			}

		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, e.getLocalizedMessage());
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.getLocalizedMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getLocalizedMessage());
		} catch (ParseException e) {
			Log.e(TAG, e.getLocalizedMessage());
		} catch (JSONException e) {
			Log.e(TAG, e.getLocalizedMessage());
		}
	}

	private String getLocalURL(Bitmap bt) {
		FileOutputStream fos = null;
		String strAvatarFilename = FileManager.getScreenShotPath() + System.currentTimeMillis() + ".png";
		try {
			fos = new FileOutputStream(strAvatarFilename);
			if (null != fos) {
				bt.compress(Bitmap.CompressFormat.PNG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strAvatarFilename;
	}

	private Bitmap imageZoom(Bitmap bmp, double maxSize) {
		// 图片允许最大空间 单位：KB
		// double maxSize =400.00;
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		Bitmap bitMap = bmp;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] b = baos.toByteArray();
		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		while (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i), bitMap.getHeight() / Math.sqrt(i));
			mid = bmpToByteArray(bitMap, false).length / 1024;
		}
		return bitMap;
	}

	public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
		return bitmap;
	}

	byte[] bmpToByteArray(final Bitmap bmp, boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
